package mobi.yuanshen.common.handler;


import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import lombok.extern.slf4j.Slf4j;
import mobi.yuanshen.common.Exception.CatterBaseException;
import mobi.yuanshen.common.Exception.ParamException;
import mobi.yuanshen.common.utils.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 全局异常拦截 
    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handlerException(Exception e) {
        e.printStackTrace();
        if (e instanceof NotRoleException) {
            return Result.failureError(403, "无此角色");
        }else if (e instanceof NotPermissionException){
            return Result.failureError(403, "无此权限");
        }else if (e instanceof DisableServiceException) {
            return Result.failureError(403, "账号被封禁");
        }
        return Result.failure(e.getMessage());
    }

    //捕获未登录异常
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result handlerNotLogin(NotLoginException e) {
        e.printStackTrace();
        log.error("出现了NotLoginException异常:" + e.getMessage());
        return Result.failureError(401,e.getMessage());
    }


    //捕获自定义异常
    @ExceptionHandler(CatterBaseException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result baseHandler(CatterBaseException e) {
        e.printStackTrace();
        log.error("出现了FitnessClubException异常:" + e.getMessage());
        return Result.failureError(e.getCode(),e.getMsg());
    }

    //捕获参数异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ParamException.class)
    public Result handlerParamException(ParamException e) {
        e.printStackTrace();
        log.error("出现了ParamException异常:" + e.getMessage());
        return Result.failureError(e.getCode(),e.getMsg());
    }


}
